<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="title" width="700px" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm">
      <template #secretSetting="{ model, field }">
        <a @click="openSecretSetting(model)">
          {{ !model["isSettingSecret"] ? "设置" : "查看" }}
        </a>
      </template>
      <template #accessTokenValidity="{ model, field }">
        <a-form-item-rest>
          <a-input-group compact>
            <a-input
              v-model:value="accessTokenValidityTime.days"
              style="width: 20%"
              addon-after="天"
              @change="(e) => handleTimeInput(accessTokenValidityTime, 'days', e)"
            />
            <a-input
              v-model:value="accessTokenValidityTime.hours"
              style="width: 20%"
              addon-after="时"
              @change="(e) => handleTimeInput(accessTokenValidityTime, 'hours', e)"
            />
            <a-input
              v-model:value="accessTokenValidityTime.minutes"
              style="width: 20%"
              addon-after="分"
              @change="(e) => handleTimeInput(accessTokenValidityTime, 'minutes', e)"
            />
          </a-input-group>
        </a-form-item-rest>
      </template>
      <template #refreshTokenValidity="{ model, field }">
        <a-form-item-rest>
          <a-input-group compact>
            <a-input
              v-model:value="refreshTokenValidityTime.days"
              style="width: 20%"
              addon-after="天"
              @change="(e) => handleTimeInput(refreshTokenValidityTime, 'days', e)"
            />
            <a-input
              v-model:value="refreshTokenValidityTime.hours"
              style="width: 20%"
              addon-after="时"
              @change="(e) => handleTimeInput(refreshTokenValidityTime, 'hours', e)"
            />
            <a-input
              v-model:value="refreshTokenValidityTime.minutes"
              style="width: 20%"
              addon-after="分"
              @change="(e) => handleTimeInput(refreshTokenValidityTime, 'minutes', e)"
            />
          </a-input-group>
        </a-form-item-rest>
      </template>
    </BasicForm>
    <Divider type="vertical" />
    <div ref="tableRef">
      <BasicTable @register="registerTable">
        <template #checked="{ record }">
          <Switch v-model:checked="record.checked" checked-children="启用" size="default" un-checked-children="禁用" />
        </template>
      </BasicTable>
    </div>

    <SecretSetting @register="registerModal" @success="secretSettingSuccess" />
    <VerifyModal @register="registerVerify" :submitCallback="handleSubmitVerify" />
    <!-- <LdpConnectDetail @register="registerExtLdpConnectDetail" /> -->
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, nextTick } from "vue"
  import { Divider, Switch, Button } from "ant-design-vue"
  import { BasicTable, BasicColumn, useTable } from "/@/components/Table"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { formSchema, extLdpColumns } from "./data"
  import { saveOrUpdate, getById, getSecret, listExtLdpConn } from "./api"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { PageEnum } from "/@/enums/pageEnum"
  import { useModal } from "/@/components/Modal"
  import SecretSetting from "./components/SecretSetting.vue"
  // import LdpConnectDetail from "/@/views/extLdp/connect/LdpConnectDetail.vue"
  import { BizType } from "/@/api/sys/model/msgPushModel"
  import { VerifyModal } from "/@/components/BizVerify"
  import * as timeUtils from "/@/utils/timeUtils"
  import { useDrawer } from "/@/components/Drawer"
  
  const { createMessage } = useMessage()
  const tableRef = ref<HTMLElement>()
  const emit = defineEmits(["register", "success"])
  const isUpdate = ref(true)
  const isDetail = ref("1")
  const record = ref<any>({})
  const accessTokenValidityTime = ref<any>({
    days: 2,
    hours: 0,
    minutes: 0,
  })
  const refreshTokenValidityTime = ref<any>({
    days: 7,
    hours: 0,
    minutes: 0,
  })

  // const [registerExtLdpConnectDetail, { openDrawer: openExtLdpConnectDetail }] = useDrawer()
  const [registerVerify, { openModal: openVerify }] = useModal()
  const [registerModal, { openModal }] = useModal()
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    schemas: formSchema,
    showActionButtonGroup: false,
    wrapperCol: { lg: 24, md: 24 },
  })

  const actionColumn: BasicColumn = {
    width: 60,
    title: "操作",
    dataIndex: "action",
    helpMessage: "由处理业务的主租户管理, 管理场景租户一般不做配置",
    fixed: "right",
    slot: "tableActions",
    actions: (record: Recordable) => [
      {
        label: "详情",
        onClick: handleExtLdpDetail.bind(null, record),
      },
    ],
  }

  const [registerTable, { reload, setProps, getDataSource }] = useTable({
    title: "外部身份源",
    columns: extLdpColumns,
    api: listExtLdpConn,
    rowKey: "grantType",
    immediate: false,
    showIndexColumn: false,
    striped: true,
    useSearchForm: false,
    showTableSetting: false,
    clickToRowSelect: false,
    pagination: false,
    bordered: false,
    // 是否可以自适应高度
    // canResize: false,
    actionColumn,
    scroll: {
      y: 10000,
    },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    console.log("record: ", data.record)

    setDrawerProps({ confirmLoading: false, loading: true})
    try {
      isUpdate.value = !!data?.isUpdate
      isDetail.value = !!data?.isDetail ? "1" : "0"
      if (unref(isUpdate)) {
        record.value = await getById({ id: data.record.id })
        setProps({ searchInfo: { id: unref(record.value.id) } })
        accessTokenValidityTime.value = timeUtils.secondsToDaysHoursMinutes(record.value.accessTokenValidity)
        refreshTokenValidityTime.value = timeUtils.secondsToDaysHoursMinutes(record.value.refreshTokenValidity)
        await setFieldsValue({
          ...record.value,
          scope: record.value.scope.join(","),
          isDetail: isDetail.value,
        })
      }
      reload()
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const title = computed(() => (!unref(isUpdate) ? "新增" : "编辑"))

  const handleExtLdpDetail = (record) => {
    // window.open(`${PageEnum.CONFIG_CENTER}?configKey=${record.configKey}`)
    // openExtLdpConnectDetail(true, { id: record.id })
  }

  const handleTimeInput = (model, field, e) => {
    console.log("input-change", e)
    nextTick(() => {
      // 限制只能输入数字
      model[field] = model[field].replace(/[^\-?\d.]/g, "")
    })
  }
  async function handleSubmit(v) {
    try {
      const extGrantTypes = await getDataSource()
        .filter((e) => e.checked)
        .map((e) => e.grantType)
        .join(",")
      if (isDetail.value === "1") {
        closeDrawer()
        return
      }
      let values = await validate()
      values.roleIds = values.roleIds ? values.roleIds.split(",") : undefined
      setDrawerProps({ confirmLoading: true })

      const form = { ...values, extGrantTypes }
      form.accessTokenValidity = timeUtils.daysHoursMinutesToSeconds(accessTokenValidityTime.value)
      form.refreshTokenValidity = timeUtils.daysHoursMinutesToSeconds(refreshTokenValidityTime.value)
      console.log("form", form)

      await saveOrUpdate(form, isUpdate.value)
      closeDrawer()
      emit("success")
      createMessage.success(`${unref(title)}成功`)
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const openSecretSetting = async (model) => {
    const { id, isSettingSecret, isShowSecretVerify, tenantOwner } = record.value
    if (isShowSecretVerify) {
      openVerify(true, {
        verifyType: "verifyEmail",
        email: {
          value: tenantOwner?.email,
          encryptData: tenantOwner?.emailEncryptData,
        },
        phone: {
          value: tenantOwner?.phone,
          encryptData: tenantOwner?.phoneEncryptData,
        },
        title: "请联系企业拥有者进行安全认证",
        bizType: BizType.SHOW_OAUTH_CLIENT_SECRET,
      })
      return
    }

    const data = await getSecret({ id })
    openModal(true, {
      record: data,
      isDetail: false,
    })
  }

  const handleSubmitVerify = async (data) => {
    console.log("submitVerify: ", data)
    setDrawerProps({ loading: true })
    try {
      const secretData = await getSecret({ id: record.value.id, ...data })
      record.value.isShowSecretVerify = false
      openModal(true, {
        record: secretData,
        isDetail: false,
      })
      console.log("accessKeyDetails: ", record.value)
    } finally {
      setDrawerProps({ loading: false })
    }
  }

  const secretSettingSuccess = async (data) => {
    const verifyData = {
      taskCode: data.taskCode,
      bizType: data.bizType,
      verifyCode: data.verifyCode,
      encryptData: data.encryptData,
    }
    record.value = { ...record.value, ...verifyData }
    await setFieldsValue({
      ...record.value,
      scope: record.value.scope.join(","),
      isDetail: isDetail.value,
    })
    emit("success")
  }
</script>

<style lang="less">
  // .ant-table td { white-space: nowrap; }
</style>
